<?php
/*
 * @Author: an
 * @Date: 2021/12/7
 * @Description: 音视频通讯
 */


namespace App\Http\Controllers\Api;


use App\Models\ImCommunicationLogs;
use App\Models\User;
use App\Services\Agora\RtcTokenService;
use App\Services\Aliyun\AudioAndVideo\RtcTokenService as AliRtcTokenService;
use Illuminate\Http\Request;

class AudioAndVideoController
{
    /**
     * 获取阿里音视频通话令牌
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author an
     * @time 2021-12-07 12:59
     */
    public function aliRtcToken(Request $request)
    {
        $user_id = $request->user()->id;
        $rtcToken = new AliRtcTokenService();
        $channel = get_uuid();//频道
        $data = $rtcToken->get($channel, $user_id);
        return okBack($data);
    }

    /**
     * 获取声网音视频通话令牌
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author an
     * @time 2021-12-07 15:33
     */
    public function agoraRtcToken(Request $request)
    {
        $user_id = $request->user()->id;
        $role = $request->get('role');
        $agora = new RtcTokenService();
        $channel = get_uuid();//频道
        $data = $agora->get($user_id, $channel, 1, $role);
        return okBack($data);
    }

    //开始通话
    public function startCommLog(Request $request)
    {
        $user_id = $request->user()->id;
        $from = $request->post('from');//1个人通话 2群通话
        $type = $request->post('type');//1.语音 2.视频
        $recipient = $request->post('recipient');//接收者id
        $channel = $request->post('channel');//通道名称

        if ($type <= 0 || empty($recipient) || empty($channel) || $from <= 0) {
            return errBack();
        }
        $comm = new ImCommunicationLogs();
        $comm->from = $from;
        $comm->type = $type;
        $comm->initiator = $user_id;
        $comm->recipient = json_encode($recipient);
        $comm->status = '.startComm';
        $comm->channel = $channel;
        $comm->duration = 0;
        $comm->save();
        return okBack([
            'logId' => $comm->id
        ]);
    }

    //更新通话状态
    public function commStatusLog(Request $request)
    {
        $user_id = $request->user()->id;
        $logId = $request->post('logId');//记录ID
        $status = $request->post('status');//第三方定义的状态，字符串
        $duration = $request->post('duration');//通话时长
        if ($logId <= 0 || empty($status) || !is_numeric($duration)) {
            return errBack();
        }
        $log = ImCommunicationLogs::where('initiator', $user_id)->find($logId);
        if (!$log) {
            return errBack('记录不存在');
        }
        $log->status = $status;
        $log->duration = $duration;
        $log->save();
        return okBack();
    }
}
